<?php 
	function player($id="", $name="", $gender="", $colour="", $university="") {
		$colours = array(
			"#FF0000" => "Red car",
			"#00FF00" => "Green car",
			"#0000FF" => "Blue car",
			"#FFFF00" => "Yellow car",
			"#000000" => "Black car",
			"#FF0099" => "Hot pink car",
			"#CC00FF" => "Purple car",
			"#FF8800" => "Orange car",
			"#CCCCCC" => "Silver car"
		);
		$newplayer = ($id=="");
?>
		<tr class="player">
			<td>
				<input type="hidden" name="id[]" value="<?= $id; ?>"/>
				<input type="<?= ($newplayer ? "text" : "hidden") ?>" name="name[]" value="<?= $name; ?>"/>
				<?= ($newplayer ? "" : $name) ?>
			</td>
			<td class="gender">
				<?php if ($newplayer) { ?>
				<span class="gender-example"></span>
				<?php } ?>
				<select name="gender[]"<?= ($newplayer ? "" : " style=\"display:none;\"") ?>>
					<option value="">Choose...</option>
					<option value="0"<?= ($gender==="0" ? " selected" : "") ?>>Male</option>
					<option value="1"<?= ($gender==="1" ? " selected" : "") ?>>Female</option>
				</select>
				<?php if (!$newplayer) {
					echo '<img src="images/icons/' . ($gender=="0"?"male":"female") . '.png"/> ' . ($gender=="0"?"Male":"Female"); 
				} ?>
			</td>
			<td class="colour">
				<span class="colour-example"></span>
				<select name="colour[]">
					<option value="">Choose car...</option>
					<?php 
						foreach ($colours as $colourcode => $colourdesc) {
							echo "<option value=\"$colourcode\"" . 
									($colourcode == $colour ? " selected" : "") . ">$colourdesc</option>";
						} 
					?>
				</select>
			</td>
			<td class="university">
				<select name="university[]">
					<option value="">Choose job/uni...</option>
					<option value="0"<?= ($university==="0" ? " selected" : "") ?>>Working</option>
					<option value="1"<?= ($university==="1" ? " selected" : "") ?>>Studying</option>
				</select>
			</td>
			<td class="actions">
				<input type="button" value="Remove" class="remove"/>
			</td>
		</tr>
<?php
	}
	
	// Includes
	include_once "db/db.php";
	
	// Update
	if (isset($_POST['name'])) {
		
		$playerids = array();
		
		// Add game players
		foreach ($_POST['name'] as $index => $name) {
			$playerid = $_POST['id'][$index];
			if ($_POST['id'][$index] == "") {
				// Create new player
				$datetime = current_date_time();
				mysql_query("
					INSERT INTO `player` (`name`, `gender`, `created`) 
					VALUES ('$name', '" . $_POST['gender'][$index] . "', '$datetime')");
				$playerid = mysql_result(mysql_query("SELECT `id` FROM `player` WHERE `created` = '$datetime'"), 0);
			}
			// Create/modify game player record
			if (mysql_num_rows(mysql_query("SELECT * FROM `gameplayer` WHERE `game` = '$current_game_id' AND `player` = '$playerid' LIMIT 1")) == 0) {
				// Create game player record
				mysql_query("
					INSERT INTO `gameplayer` (`game`, `player`, `colour`, `university`) 
					VALUES ('$current_game_id', '$playerid', 
						'" . $_POST['colour'][$index] . "', 
						'" . $_POST['university'][$index] . "')");
			} else {
				// Modify game player record
				mysql_query("
					UPDATE `gameplayer` 
					SET `colour` = '" . $_POST['colour'][$index] . "', 
						`university` = '" . $_POST['university'][$index] . "' 
					WHERE `game` = '$current_game_id' AND `player` = '$playerid' 
					LIMIT 1;");
			}
			array_push($playerids, $playerid);
		}
		
		// Remove game players
		$playerids_condition = "(`player` != '" . implode("' AND `player` != '", $playerids) . "')";
		mysql_query("DELETE FROM `gameplayer` WHERE `game` = '$current_game_id' AND $playerids_condition");
	
		header("location:play.php");
	}
	
	// Contents
	include_once "header.php";
?>

<script type="text/javascript">
	jQuery(document).ready(function () {
		
		var playerEvents = function (player) {
			// Colour
			player.find("select[name='colour[]']").change(function () {
				jQuery(this).prev().css("background-color", jQuery(this).val());
			}).change();
			// Gender
			player.find("select[name='gender[]']").change(function () {
				jQuery(this).prev().html("<img src=\"images/icons/" + (jQuery(this).val() === "0" ? "male" :
					(jQuery(this).val() === "1" ? "female" : "unknown")) + ".png\"/ >");
			}).change();
			// Delete
			player.find("input.remove").click(function () {
				jQuery(this).parent().parent().remove();
			});
		};
		
		// Add player
		jQuery("#addNewPlayer").click(function () {
			var player = jQuery("#player-template .player").clone();
			jQuery("#players").append(player);
			playerEvents(player);
		});
		jQuery("#existingPlayers").change(function () {
			var option = jQuery(this).find("option:selected"),
			// Create player
			player = jQuery("#player-template-existing .player").clone();
			// Set ID
			player.find("input[name='id[]']").val(option.attr("value"));
			// Set name
			player.find("input[name='name[]']").val(option.attr("name")).after(option.attr("name"));
			// Set gender
			player.find("td.gender").html(
				"<img src=\"images/icons/" + (option.attr("gender")=="0"? "male" : "female") + ".png\" / > " +
				(option.attr("gender")=="0"? "Male" : "Female")
			);
			
			// Display
			jQuery("#players").append(player);
			playerEvents(player);
			// Remove from list of options
			option.remove(); 
		});
		
		// Assign events to initial players
		jQuery("#players .player").each(function (index, element) {
			playerEvents(jQuery(element));
		});
		
		// Cancel button
		jQuery("#btnCancel").click(function () {
			window.location = "play.php";
		});
		
	});
</script>
<style type="text/css">
	table#players {
		margin: 20px auto 20px auto;
	}
</style>

<select id="existingPlayers">
	<option value="">+ Add existing player...</option>
	<?php
		$player_query = mysql_query("
			SELECT `player`.* 
			FROM `player` 
				LEFT JOIN `gameplayer` 
					ON (`player`.`id` = `gameplayer`.`player` AND `gameplayer`.`game` = '$current_game_id')
			WHERE `gameplayer`.`game` IS NULL
			ORDER BY `player`.`name`");
		while ($player = mysql_fetch_assoc($player_query)) {
			echo "\t<option value=\"" . $player['id'] . "\" name=\"" . $player['name'] . "\" gender=\"" . $player['gender'] . "\">" . $player['name'] . " (" . ($player['gender'] == 0 ? "male" : "female") . ")</option>\n";
		}
	?>
</select>
<input type="button" value="+ New Player" id="addNewPlayer"/>

<table id="player-template" style="display:none">
<?php player(); ?>
</table>
<table id="player-template-existing" style="display:none">
<?php player("0"); ?>
</table>

<form method="post" action="config.php">
<table id="players">
	<tr>
		<th style="width:200px;">Player name</th>
		<th>Gender</th>
		<th>Car colour</th>
		<th>Work or Uni?</th>
		<th></th>
	</tr>
<?php
	$player_query = mysql_query("
		SELECT `player`.*, `gameplayer`.* FROM `player`, `gameplayer` 
		WHERE `player`.`id` = `gameplayer`.`player` AND `gameplayer`.`game` = '$current_game_id'
		ORDER BY `player`.`name`");
	while ($player = mysql_fetch_assoc($player_query)) {
		player($player['id'], $player['name'], $player['gender'], $player['colour'], $player['university']);
	}
?>
</table>

<div id="actions">
	<input type="submit" value="Save" id="btnSave"/>
	<input type="reset" value="Cancel" id="btnCancel"/>
</div>
</form>

<form method="post" action="config.php" id="frmDelete" style="display:none;">
	<input id="deleteId" name="delete" value=""/>
	<input type="submit" id="deleteSubmit" />
</form>

<?php include_once "footer.php"; ?>
